<?php

namespace LaiHe\LaravelHelper\Http\Resources;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\Pivot;
use Illuminate\Http\Resources\Json\JsonResource;
use LaiHe\LaravelHelper\Eloquent\Model;

/**
 * 混淆资源id
 *
 * @mixin \LaiHe\LaravelHelper\Eloquent\Model
 * @package App\Http\Resources
 */
class HashIdsResource extends JsonResource
{
	/**
	 * @inheritDoc
	 */
	public function toArray($request)
	{
		$keyName        = $this->getKeyName();
		$data           = parent::toArray($request);
		$data[$keyName] = $this->encodeValue($keyName);
		foreach($this->getRelations() as $name => $relation){
			if($relation instanceof Pivot){
				unset($data[$name]);
			}else if($relation instanceof Model){
				$data[$name] = (new static($relation))->resolve($request);
			}else if($relation instanceof Collection){
				$data[$name] = static::collection($relation)->resolve($request);
			}
		}

		return $data;
	}
}
